import React, { useState } from 'react'
import { useRef } from 'react'

export default function FormOutControl() {
    const submitHandler = (e)=>{
        console.log('username:' , usernameRef.current.value)
        console.log('password:' , passwordRef.current.value)
        console.log('sex:' , sexRef.find(item=>item.current.checked).current.value)
        console.log('city:' , cityRef.current.value)
        console.log('hobby:' , hobbyRef.filter(item=>item.current.checked).map(item=>item.current.value))
        e.preventDefault()
    }
    // 1. 定义ref
    const usernameRef = useRef()
    const passwordRef = useRef()
    const sexRef = [useRef(),useRef()]
    const cityRef = useRef()
    const hobbyRef = [useRef(),useRef(),useRef(),useRef()]

    // 定义状态数据
    let [username, setUsername] = useState('yuonly')
    let [password, setPassword] = useState('123123')
    let [sex, setSex] = useState('1')
    let [city, setCity] = useState('1')
    let [hobby, setHobby] = useState(['1','3'])

    return (
        <div>
            <form onSubmit={submitHandler}>
                <p>用户名: <input type="text" name="username" defaultValue={username}  ref={usernameRef}/></p>
                <p>密  码: <input type="text" name="password" defaultValue={password}  ref={passwordRef}/></p>
                <p>
                    性别：
                    <input type="radio" name="sex" value="1" defaultChecked={sex==='1'} ref={sexRef[0]}/> 男
                    <input type="radio" name="sex" value="0" defaultChecked={sex==='0'} ref={sexRef[1]}/> 女
                </p>
                <p>
                    city: 
                    <select name="city" defaultValue={city} ref={cityRef}>
                        <option value="1">北京</option>
                        <option value="2">深圳</option>
                        <option value="3">上海</option>
                    </select>
                </p>
                <p>
                    爱好：
                    <input type="checkbox" name="hobby" value="1" defaultChecked={hobby.includes('1')} ref={hobbyRef[0]}/> 台球
                    <input type="checkbox" name="hobby" value="2" defaultChecked={hobby.includes('2')} ref={hobbyRef[1]}/> 羽毛球
                    <input type="checkbox" name="hobby" value="3" defaultChecked={hobby.includes('3')} ref={hobbyRef[2]}/> 乒乓球
                    <input type="checkbox" name="hobby" value="4" defaultChecked={hobby.includes('4')} ref={hobbyRef[3]}/> 溜溜球
                </p>
                <button>提交</button>
            </form>
        </div>
    )
}
